package bidsanity

class BidController {

    def index() {
        [bidInstanceList: Bid.list(sort: "listing"), bidInstanceTotal: Bid.count()]
    }

    def create() {
        [bidInstance: new Bid(params)]
    }

    def save() {

        if(params.amount == null || !params.amount.isDouble())  {
                flash.message = message(code: 'bid.was.not.valid', args: [])
                redirect(controller: "Listing", action: "show", id: params.listing.id)
                return
            }
        def listingInstance = Listing.get(params.listing.id)
        def bidInstance = new Bid(params)

        if (listingInstance.seller == bidInstance.bidder) {
            flash.message = message(code: 'bid.sameperson', args: [bidInstance.bidder.getNameFromEMail()])
            redirect(controller: "Listing", action: "show", id: params.listing.id)
            return
        }

        listingInstance.addToBids(bidInstance)

        if (!listingInstance.save(failOnError: false, validate: true))   {
                flash.message = message(code: 'bid.bid.too.low', args: [String.format('$%.2f', bidInstance.amount)])
                redirect(controller: "Listing", action: "show", id: params.listing.id)
                return
        }

        
        flash.message = message(code: 'bid.successful', args: [bidInstance.bidder.getNameFromEMail()])
        redirect(controller: "Listing", action: "show", id: params.listing.id)
    }
}
